# -*- coding: utf-8 -*-
############################################################################
from chee.shortcuts import *
from chee.models import User_Info,Misc_Country,Misc_Area
from chee.models.user import *
############################################################################
class UserMain(UserHandler):
    rule = Rule("/user/")
    def get(self):
        tmpl = env.get_template('user/myspace.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, main_active = u"myspace", acts = recent_acts,
            other_watches = other_watches
        ))
class UserFromOther(AuthHandler):
    rule = Rule("/user/<int:user_id>/")
    def get(self):
        user_id = self.kwargs['user_id']
        usr = store.find(User_Info,User_Info.id==user_id).one()
        if not usr: return ShowInfo(self.request,self.errors,u'没有该用户的信息')

        tmpl = env.get_template('user/user_info.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, main_active = u"myspace",
            this_user = usr, acts = recent_acts, other_watches = other_watches
        ))
class UserChange(UserHandler):
    rule = Rule("/user/change/")
    def get(self):
        db = self.store
        areas = store.find(Misc_Area)
        
        tmpl = env.get_template('user/change_me.html')
        return Response(tmpl.render(
            request = self.request,
            errors = self.errors,
            main_active = u"myspace",
            areas = areas
        ))
    def post(self):
        try:
            nick_name = self.request.form.get('nick', u'').strip()
#            gender = int(self.request.form.get('gender','').strip())
#            area_id = int(self.request.form.get('area','').strip())
#            blog = self.request.form.get('blog','').strip()
#            sig = self.request.form.get('sig','').strip()
            
            if not nick_name:
                return  Response(encodeJsonMsg(False,u'必须输入昵称' % bw))
            if len(nick_name) > 12:
                return  Response(encodeJsonMsg(False,u'昵称长度不能大于12个字，请更换' % bw))
#            if sig and len(sig) > 200:
#                return  Response(encodeJsonMsg(False,u'个人介绍长度不能大于200个字，请更换' % bw))
            bw = strict_ban_word(nick_name)
            if bw:
                return  Response(encodeJsonMsg(False,u'您的昵称包含敏感词汇\"%s\"，请更换' % bw))
#            bw = strict_ban_word(sig)
#            if bw:
#                return  Response(encodeJsonMsg(False,u'您的个人介绍包含敏感词汇\"%s\"，请更换' % bw))
            
            usr = store.find(User_Info,User_Info.id==self.request.user.id).one()
    
            usr.nick_name = toHtml(nick_name)
#            usr.gender = gender
#            usr.area_id = area_id
#            blog = blog.lower()
#            if blog.find('http://') < 0:
#                blog = 'http://%s' % blog
#            if blog.strip() == 'http://':
#                blog = u''
#            usr.blog = blog
#            usr.signature = toHtml(sig)
    
            store.add(usr)
            store.commit()
            
            self.request.user = usr
            cache.delete('user_item_%d'%usr.id)
            return Response(encodeJsonMsg(True, nick_name))
        except:
            return Response(encodeJsonMsg(False, u'发送数据出错，请联系管理员'))

class Change_User_Image(UserHandler):
    rule = Rule("/user/chg_img/")
    def get(self):
        tmpl = env.get_template('tool/upload_user_image.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, main_active = u"myspace"
        ))
    def post(self):
        usr = self.store.find(User_Info,User_Info.id==self.request.user.id).one()
        import os,Image
        self.errors['up_file'] = u''
        up_file = self.request.files.get('up_file')
        if not up_file:
            self.errors['up_file'] = u'没有文件'
            return self.get()
        # 判断后缀,支持
        support_suffix = [".jpg",".bmp",".gif",".png"]
        (fname,suffix) = os.path.splitext(up_file.filename)
        suffix = suffix.lower()
        if not (suffix in support_suffix):
            self.errors['up_file'] = u'请上传图片文件，支持jpg/bmp/gif/png格式'
            return self.get()
        user_folder = pathHelper.getUserFolderAbs(self.request.user_id)
        if not os.path.exists(user_folder): os.makedirs(user_folder) 
        only_file_name = getRandomName(); save_file_name = only_file_name + suffix
        
        f = open(os.path.join(user_folder, save_file_name), 'wb')
        while True:
            s = up_file.read(10 ** 6)
            if s: f.write(s)
            else: f.close(); break
        suffix = ''
        my_img = None
        try: my_img = Image.open(os.path.join(user_folder, save_file_name))
        except: pass
        if my_img == None: # 打不开文件不作处理
            self.errors['up_file'] = u'处理图片文件出错，可能是不支持的图片文件格式!'
            try: os.remove(os.path.join(user_folder,save_file_name))
            except:pass
            return self.get()
        else:
            format = my_img.format
            if format == 'BMP': format = 'JPEG'
            if format == 'JPEG': suffix = u'.jpg'
            else: suffix = u'.%s' % format.lower()
            large_img_name = u'l_user_%s%s' % (only_file_name,suffix)
            normal_img_name = u'user_%s%s' % (only_file_name,suffix)
            temp_img_name = u'temp_%s%s' % (only_file_name,suffix)
            # 首先保存一份120定高度缩略图,然后切一个50*50的小图
            # 保存文件前需要先删除原有文件
            (origin_width,origin_height) = my_img.size
            if origin_height < 120:
                my_img = my_img.convert("RGB", dither=Image.NONE, palette=Image.ADAPTIVE)
                my_img.save(os.path.join(user_folder, large_img_name),format,quality=96)
            else:
                now_height = 120
                now_width = int(now_height * origin_width / origin_height)
                my_img.convert("RGB", dither=Image.NONE, palette=Image.ADAPTIVE)
                my_img = my_img.resize((now_width,now_height), Image.ANTIALIAS)
                my_img.save(os.path.join(user_folder, large_img_name),format,quality=96)
            
            my_img = Image.open(os.path.join(user_folder, save_file_name))
            if origin_width >= origin_height:
                now_height = 50
                now_width = int(now_height * origin_width / origin_height)
                my_img = my_img.convert("RGB", dither=Image.NONE, palette=Image.ADAPTIVE)
                my_img = my_img.resize((now_width,now_height), Image.ANTIALIAS)
                x_from = (now_width-50)/2
                crop_box = (x_from,0,50+x_from,50)
                crop_img = my_img.crop(crop_box)
                crop_img.save(os.path.join(user_folder, normal_img_name),format,quality=96)
            else:
                now_width = 50
                now_height = int(now_width * origin_height / origin_width )
                my_img = my_img.convert("RGB", dither=Image.NONE, palette=Image.ADAPTIVE)
                my_img = my_img.resize((now_width,now_height), Image.ANTIALIAS)
                y_from = (now_height-50)/2
                crop_box = (0,y_from,50,50+y_from)
                crop_img = my_img.crop(crop_box)
                crop_img.save(os.path.join(user_folder, normal_img_name),format,quality=96)

            try:
                os.remove(os.path.join(user_folder, usr.photo))
                os.remove(os.path.join(user_folder, 'l_'+usr.photo))
                os.remove(os.path.join(user_folder, temp_img_name))
                os.remove(os.path.join(user_folder, save_file_name))
            except:
                pass
        usr.photo = normal_img_name
        self.store.add(usr); self.store.commit()
        
        self.request.user = usr
        cache.delete('user_item_%d'%usr.id)
        self.errors['up_file'] = u'上传成功'
        tmpl = env.get_template('tool/upload_user_image.html')
        return Response(tmpl.render(    
            request = self.request,
            errors = self.errors,
            main_active = u"myspace"
        ))
class Reset_Password(AuthHandler):
    rule = Rule('/user/reset_pass/')
    def get(self):
        tmpl = env.get_template('user/reset_pass.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, main_active = u"myspace"
        ))
    def post(self):
        db = self.store
        my_acc = self.request.form.get('my_acc')
        usr = store.find(User_Info,User_Info.name==my_acc).one()
        if usr == None:
            self.errors['reset_pass'] = u'找不到该注册邮箱'
            return self.get()
        if not usr.email:
            self.errors['reset_pass'] = (
                u'非常遗憾，您是历史账号，没有填写注册邮箱，请发信到(%s)进行人工取回密码' % (
                u'admin@chee.com'))
            return self.get()
        now_pass = self.getRandomPassword()
        # need md5_hash, as java script hashed password on client
        import md5
        from chee.mailHelper import E_mail
        now_pass_hash = md5.new(now_pass).hexdigest()
        usr.setPassword(now_pass_hash)
        store.add(usr)
        store.commit()
        # send user an outer email
        o_mail = E_mail()
        o_mail.mail_from = u'hello<hello@chee.com>'
        o_mail.mail_to = [usr.name]
        o_mail.mail_subject = u'重置用户密码 '
        o_mail.mail_content = (
            u'亲爱的%s:<br />你好！<br />' % usr.nick_name + 
            u'你的新密码是:%s <br />' % now_pass +
            u'为了您的账户安全，建议您马上登录并修改密码。' + 
            u'<a href="http://%s" target="_blank">%s</a>' % (self.request.host,self.request.host)
            )
        try:
            o_mail.send()
            self.errors['reset_pass'] = u'已经将您的密码发送到您的注册邮箱，请查收'
        except: 
            self.errors['reset_pass'] = u'暂时无法发送邮件到您的邮箱，请稍后重试'
        return self.get()
    def getRandomPassword(self):
        from_int = 97
        to_int = 122
        word_count = 6
        password = ''
        import random
        for i in range(6):
            password = password + chr(random.randint(from_int,to_int))
        return password
    def md5_hash(self,password):
        import md5
        return md5.new(password).hexdigest()
class User_Change_Pass(UserHandler):
    rule = Rule("/user/change_pass/")
    def get(self):
        tmpl = env.get_template('user/change_pass.html')
        return Response(tmpl.render(
            request = self.request,
            errors = self.errors,
            main_active = u"myspace"
        ))
    def post(self):
        former_pass = self.request.form.get('former_password', u'').strip()
        password = self.request.form.get('password', u'').strip()
        if self.request.user.checkPassword(former_pass):
            db = self.store
            usr = store.find(User_Info,User_Info.id==self.request.user_id).one()
            usr.setPassword(password)
            store.add(usr)
            store.commit()
            self.errors['chg_pass'] = u'更改密码成功'
        else:
            self.errors['chg_pass'] = u'原密码错误'
            
        return self.get()
class UserFriend_Add(UserAjaxHandler):
    rule = Rule("/user/friend/new/")
    def post(self):
        try:
            db = self.store
            user_id = int(self.request.form.get('user_id'))
            User_Remind.add_friend_request(self.request.user,user_id)
            return Response(encodeJsonMsg(True,u''))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))
class UserFriend_Agree(UserAjaxHandler):
    rule = Rule("/user/friend/agree/")
    def post(self):
        try:
            db = self.store
            remind_id = int(self.request.form.get('remind_id'))
            User_Remind.agree_friend(remind_id)
            return Response(encodeJsonMsg(True,u''))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))
class UserFriend_Reject(UserAjaxHandler):
    rule = Rule("/user/friend/reject/")
    def post(self):
        try:
            db = self.store
            remind_id = int(self.request.form.get('remind_id'))
            User_Remind.del_remind(remind_id)       
            return Response(encodeJsonMsg(True,u''))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))
class UserFriend_Delete(UserAjaxHandler):
    rule = Rule("/user/friend/delete/")
    def post(self):
        try:
            db = self.store
            user_id = int(self.request.form.get('user_id'))
            friend = store.find(User_Friend,
                    User_Friend.owner_id==self.request.user.id,
                    User_Friend.friend_id==user_id)
            # 如果不是自己
            if friend.one().owner_id != self.request.user_id:
                return Response(encodeJsonMsg(False,u'您没有权限'))
            friend.remove()
            store.find(User_Friend,
                    User_Friend.friend_id==self.request.user.id,
                    User_Friend.owner_id==user_id).remove()
            store.commit()        
            return Response(encodeJsonMsg(True,u''))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))
class UserFriend_List(AuthHandler):
    rule = Rule("/user/<int:user_id>/friend/")
    def get(self):
        db = self.store
        user_id = self.kwargs['user_id']
        
        v_friends = store.find(User_Friend,
                       User_Friend.owner_id==user_id)
        try:
            page_num = int(self.request.args.get('page', '1'))
        except ValueError:
            page_num = 1 

        paginator = Paginator(v_friends, 15) 
        try:
            page = paginator.page(page_num)
        except InvalidPage:
            raise NotFound

        tmpl = env.get_template('user/friend.html')
        return Response(tmpl.render(
            request = self.request,
            errors = self.errors,
            main_active = u"myspace",
            page = page
        ))
    def post(self):
        return self.get()
class UserSearch(AuthHandler):
    rule = Rule("/user/search/")
    def get(self):
        db = self.store
        s_word = u''
        s_conditions = u''
        if 'word' in self.request.args: s_word = self.request.args.get('word')
        elif 's_user' in self.request.form: s_word = self.request.form.get('s_user')
        q_str = u''; s_conditions = []
        s_users = []
        if s_word:
            q_str = 'word=%s&amp;' % s_word
            s_conditions.append(User_Info.nick_name.like('%' + s_word + "%"))
            s_users = store.find(User_Info,*s_conditions).order_by(Desc(User_Info.id))
        else:
            # 没有设定条件的话
            topuid = store.find(User_Info.id).order_by(Desc(User_Info.id)).config(limit=1,offset=0).one()
            fromid = random.randint(1,topuid-30)
            _users = store.find(User_Info,User_Info.id >= fromid).order_by(Asc(User_Info.id)).config(limit=30,offset=0)
            s_users = [u for u in _users]
        try: page_num = int(self.request.args.get('page', '1'))
        except ValueError: page_num = 1 

        paginator = Paginator(s_users, 30) 
        try: page = paginator.page(page_num)
        except InvalidPage: raise NotFound
        tmpl = env.get_template('user/user_list.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, main_active = u"myspace", page = page, s = q_str
        ))
    def post(self):
        return self.get()
class UserFind(AuthHandler):
    rule = Rule("/user/find/")
    def post(self):
#        try:
            s_name = self.request.form.get('nick',u'').strip()
            if not s_name: return Response(encodeJsonMsg(False,u'没有输入条件'))
            s_id = 0
            s_inner = [User_Info.nick_name.like('%' + s_name + "%")]
            s_inner.append(User_Info.name.like('%' + s_name + "%"))
            if s_name.isdigit(): s_id = int(s_name)
            if s_id: s_inner.append(User_Info.id==s_id)
            s_users = self.store.find(User_Info,Or(s_inner)).order_by(Asc(User_Info.id))
            if s_users.count() == 0: return Response(encodeJsonMsg(False,u'没有找到符合条件的用户'))
            array = []
            for u in s_users:
                arr = {}; arr['id'] = u.id; arr['name'] = u.name; arr['nick'] = u.nick_name
                arr['gender'] = u.gender==0 and u'男' or u'女'
                arr['area'] = u.area==None and u'未知位置' or u.area.name
                array.append(arr)
                if len(array) >= 30: break
            return Response(encodeJsonMsg(True,array))
#        except: return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))
class UserFindFriend(UserAjaxHandler):
    rule = Rule("/user/find/friend/")
    def get(self):
        return self.post()
    def post(self):
        try:
            db = self.store
            user_id = self.request.user.id
            v_friends = store.find(User_Friend,User_Friend.owner_id==user_id)
            except_uid = self.request.form.get('except_uid','').strip()
            except_uids = []
            if except_uid:
                uids = except_uid.split(',')
                for uidstr in uids:
                    if (not uidstr) or (not uidstr.isdigit()): continue
                    uid = int(uidstr)
                    except_uids.append(uid)
            msg = ''
            utl = GlobalUtils()
            if v_friends.count() == 0: msg = encodeJsonMsg(False,u'你还没有好友')
            else:
                array = []
                for fr in v_friends:
                    if fr.friend_id in except_uids: continue
                    arr = {}
                    arr['id'] = fr.friend_id
                    arr['name'] = fr.friend.name
                    arr['nick'] = fr.friend.nick_name
                    arr['gender'] = utl.getGender(fr.friend.gender)
                    arr['area'] = fr.friend.area==None and u'未知位置' or fr.friend.area.name
                    array.append(arr)
                msg = encodeJsonMsg(True,array)
            return Response(msg)
        except: return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))
class User_Refresh(UserAjaxHandler):
    rule = Rule('/user/refresh/')
    def post(self):
        try:
            if self.request.user.payacc_id > 0:
                from chee.models.pay import Pay_Account
                acc = store.find(Pay_Account,Pay_Account.id==self.request.user.payacc_id).one()
                if acc:
                    acc.user_active_time = datetime.now(); store.add(acc); store.commit()
            return Response(encodeJsonMsg(True,u''))
        except: return Response(encodeJsonMsg(False,u''))
class UserUtils(AuthHandler):
    rule = Rule('/user/utils/')
    def get(self):
        return self.post()
    def post(self):
        try:
            req_type = self.request.form.get('type','').strip()
            s = ""
            if req_type == u"accexist":
                usr_name = self.request.form.get('value',u'').strip()
                bw = strict_ban_word(usr_name)
                if bw: s = encodeJsonMsg(False,u'邮箱地址包含敏感词汇\"%s\",请更换' % bw)
                elif User_Info.hasUser(usr_name): s = encodeJsonMsg(False,u'该邮箱地址已经被注册')
                else: s = encodeJsonMsg(True,'')
            elif req_type == u"nickexist":
                n_name = self.request.form.get('value',u'').strip()
                count = User_Info.hasNickCount(n_name)
                s = encodeJsonMsg(True,count)
            return Response(s)
        except: return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))
    
